# Create your views here.

from django.http import HttpResponse
from django.conf.urls.defaults import *
from django.shortcuts import redirect
from django.shortcuts import render_to_response
from django.template import RequestContext
import json

urlpatterns = patterns('cart.views',
    (r'^add',    'add'),
    (r'^remove', 'remove'),
    (r'^view/$', 'view'),
    (r'^clear',  'clear'),
)

def add(request):
    try:
        shopping_cart = json.loads(str(request.session['cart']))
    except KeyError, TypeError:
        shopping_cart = []

    product_id = request.GET['product_id']
    title = request.GET['title']
    price = request.GET['price']
    vendor = request.GET['vendor']
    purchase_url = request.GET['purchase_url']

    item = {'product_id':product_id,
            'title':title,
            'price':price,
            'index':len(shopping_cart),
            'vendor':vendor,
            'purchase_url': purchase_url }

    shopping_cart.append(item)

    request.session['cart'] = json.dumps(shopping_cart,indent=4)

    total = 0.0

    for item in shopping_cart:
        total += float(item['price'])

    return HttpResponse(json.dumps({'success': True}), mimetype = 'application/json')
    #return render_to_response( "cart_view.html", {'shopping_cart': shopping_cart, 'total':total},
    #        context_instance=RequestContext(request)
    #        )

def remove(request):
    try:
        shopping_cart = json.loads(request.session['cart'])
    except KeyError:
        shopping_cart = []

    index = int(request.GET['index'])

    item = shopping_cart.pop(index)

    for i in range(len(shopping_cart)):
        shopping_cart[i]['index'] = i

    request.session['cart'] = json.dumps(shopping_cart)

    return HttpResponse(json.dumps({'success': True}), mimetype = 'application/json')
    #return render_to_response( "cart_view.html", {'shopping_cart': shopping_cart,
    #                                               'total':total},
    #        context_instance=RequestContext(request)
    #        )


def view(request):
    try:
        shopping_cart = json.loads(str(request.session['cart']))
    except:
        shopping_cart = []

    total = getTotal(shopping_cart)

    return render_to_response( "cart_view.html", {'shopping_cart': shopping_cart,
                                                   'total':total},
            context_instance=RequestContext(request)
            )

def clear(request):
    request.session['cart'] = []

    return HttpResponse(json.dumps({'success': True}), mimetype = 'application/json')
    #shopping_cart = json.loads(str(request.session['cart']))

    #return render_to_response( "cart_view.html", {'shopping_cart': shopping_cart,
    #                                               'total':0.0},
    #        context_instance=RequestContext(request)
    #        )

def getTotal(shopping_cart):
    total = 0.0

    for item in shopping_cart:
        total += float(item['price'])

    return total
